<?php
namespace App\Models\Scripts;

use App\Http\Config\ErrorCode;
use App\Library\Tools;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class v47cd76e43f74bbc2e1baaf194d07e1fa extends Sysupdate
{
    protected $version_id ='1.0.0';

    private $returnData = array('code'=>0,'message'=>'执行成功');

    public function upgrade()
    {
        $r_data = $this->_fix_order();
        if($r_data['code']>0){
            return $r_data;
        }
        return $this->returnData;
    }

    /*
     * 修复订单表
     * 1.新增goods_id 根据之前的订单商品名称商品名做匹配 然后绑定goods_id  [好多商品和订单名字对不上]
     *
     */
    private function _fix_order()
    {
        $order = DB::table('orders')->select('id','title')->get();
        $order_list = json_decode($order,true);
        $goods = DB::table('goods')->select('id','goods_name')->get();
        $goods_list = json_decode($goods,true);
        $data = [];
        foreach ($order_list as $key=>$value){
            foreach ($goods_list as $k=>$v){
                if(strpos($value['title'],'(')===FALSE){
                    if($v['goods_name']!=$value['title']){
                        continue;
                    }
                    $data[] = ['id'=>$value['id'],'goods_id'=>$v['id']];
                }else{
                    $name = explode('(',$value['title'])[0];
                    if($v['goods_name']!=$name){
                        continue;
                    }
                    $data[] = ['id'=>$value['id'],'goods_id'=>$v['id']];
                }
            }
        }
        $res = Tools::updateBatch($data,'orders');
        if(!$res){
            $this->returnData['code'] = ErrorCode::$admin_enum['fail'];
            return $this->returnData;
        }
        return $this->returnData;
    }
}
